﻿// Copyright @ shch8.com All Rights Reserved At 2008-3-6
//开发：商创技术（www.shch8.com）望月狼
package com._public._net {
	import com._public._debug.GetErrMsg;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.net.URLVariables;
	import flash.net.URLRequestMethod;
	import flash.net.URLLoaderDataFormat;
	import flash.utils.ByteArray;
	import flash.system.System;
	import flash.utils.Endian;
	/**
		·数据加载
		 例：
		 LoadData.getInstance().loadXML("room.xml", getXML)
		 //getXML为接收XML的函数
		 function getXML(xml:XML):void {
		 trace(xml)
		 }
	 */
	public class LoadData {
		private var filePath:String;
		public var getXML:Function;
		public var getFile:Function;
		public var errorFun:Function
		private var useXML:Boolean;//是否加载为XML，及二进制字节流加载中，判断是否使用低位置前顺序加载
		public var id:String = "";//加载识别ID，完成或失败加载后将传到回调函数中
		private static var loadData:LoadData
		public function LoadData() {
			
		}
		public static function getInstance(isNew:Boolean = true):LoadData {
			if (isNew) return loadData = new LoadData;
			if (loadData == null) loadData = new LoadData;
			return loadData;
		}
		/*加载XML文件,(路径，XML接收函数，是否使用中文编码)*/
		public function loadXML(_filePath:String, _getXML:Function = null,gbCode:Object=null,_useXML:Boolean=true,_errorFun:Function=null,variables:URLVariables=null):URLLoader {
			getXML = _getXML;
			errorFun = _errorFun;
			useXML = _useXML;
			//if(gbCode)throw("useCode")
			var myLoader:URLLoader = new URLLoader();
			if(gbCode!=null)System.useCodePage = gbCode;
			myLoader.addEventListener(Event.COMPLETE,xmlLoadComplete);
			myLoader.addEventListener(IOErrorEvent.IO_ERROR, loadError);
			
			var request:URLRequest = new URLRequest(_filePath);
			if(variables!=null){
			request.data = variables;
			request.method = URLRequestMethod.POST;
			}
			myLoader.load(request);
			return myLoader;
		}
		/**
		 * 加载外部文件，jpg,png,gif图片及SWF文件
		 * @param	_filePath
		 * @param	_getFile
		 * @param	_errorFun
		 * @return
		 */
		public function loadFile(_filePath:String, _getFile:Function = null,_errorFun:Function=null):Loader {
			getFile = _getFile;
			errorFun = _errorFun;
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoadComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError);
			loader.load(new URLRequest(_filePath));
			return loader;
		}
		private function imgLoadComplete(event:Event):void {
			var loader:LoaderInfo = event.target as LoaderInfo;
			loader.removeEventListener(Event.COMPLETE, imgLoadComplete);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
			if (getFile != null) (id=="")?getFile(loader.loader):getFile(loader.loader,id);
		}
		/**
		 * 二进制数据加载
		 * @param	_filePath
		 * @param	_getFile
		 * @param	_errorFun
		 * @param	littleEndian	是否使用字节流方式，指示多字节数字的最低有效字节位于字节序列的最前面。
		 * @return
		 */
		public function loadByteArray(_filePath:String, _getFile:Function = null,_errorFun:Function=null,littleEndian:Boolean=false):URLStream {
			getFile = _getFile;
			errorFun = _errorFun;
			useXML = littleEndian;
			var stream:URLStream = new URLStream();
			stream.load(new URLRequest(_filePath));
			stream.addEventListener(Event.COMPLETE, byteComplete);
			stream.addEventListener(IOErrorEvent.IO_ERROR, loadError);
			return stream;
		}
		private function byteComplete(e:Event):void {
			var stream:URLStream = e.currentTarget as URLStream;
			stream.removeEventListener(Event.COMPLETE, byteComplete);
			stream.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
			var byteData:ByteArray = new ByteArray
			if (useXML) byteData.endian = Endian.LITTLE_ENDIAN;
			stream.readBytes(byteData);
			if (getFile != null) (id=="")?getFile(byteData):getFile(byteData,id);
		}
		private function xmlLoadComplete(event:Event):void {
			  XML.ignoreWhitespace = true;
			  var loadStr:String = event.target.data;
			  if(useXML){
				  loadStr = loadStr.slice(0, loadStr.lastIndexOf(">") + 1);
				  if (getXML != null) {
					  try{
					  var _xml:XML = new XML(loadStr);
					  }catch (e:*) {
						  loadError(event)
						  }
					  (id=="")?getXML(_xml):getXML(_xml,id);
				  }
			  }else if (getXML != null) {
				  (id=="")?getXML(loadStr):getXML(loadStr,id);
			  }
		}
		private function loadError(e:Event):void {
			if (errorFun is Function) (id == "")?errorFun():errorFun(id);
			var loadObj:Object = e.currentTarget;
			loadObj.removeEventListener(Event.COMPLETE, byteComplete);
			loadObj.removeEventListener(Event.COMPLETE, imgLoadComplete);
			loadObj.removeEventListener(Event.COMPLETE, xmlLoadComplete);
			loadObj.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
		}
	}
}
